
//
//  ChoicePreferenceViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/9.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import DynamicBlurView
import Alamofire
import PKHUD
import SwiftyJSON
import MappingAce

class ChoicePreferenceViewController: BaseViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    private let RoundMargin: CGFloat = 27
    private let itemMargin: CGFloat =  6
    private let itemCount: CGFloat = 3
    private let itemHeght: CGFloat = 60
    private var datas: [Bool] = []
    private var interestMark:Array=[Any]()

    @IBOutlet weak var bgImageView: UIImageView!
    @IBOutlet weak var mainCollectionView: UICollectionView!
    @IBOutlet weak var mainCollectionViewHeight: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        //从服务器获取标签数据
        let requesturl = "\(BaseURL)\(interestMarkUrl)"
        
        Alamofire.request(requesturl, method: .post,
                          parameters: nil ,
                          encoding: URLEncoding.default,
                          headers: nil).responseJSON {
                            (response) in
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        
                                        

                                        let arr = json["data"].array!
                                        for subject in arr{
                                            let interestMarkModel = InterestMarkModel(fromDic: subject.dictionary!)
                                            print(interestMarkModel.createTime!)
                                            self.interestMark.append(interestMarkModel)
                                            self.datas.append(false)
                                            self.mainCollectionView.reloadData()
                                        }

                                        print(self.interestMark)
                                        
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }
                            
        }
        // Do any additional setup after loading the view.
    }
    
    func setUI() {
//        datas = SelectData(names: itemImageNames.flatMap({$0.0}))
        let layout = UICollectionViewFlowLayout()
        let itemWidth = (ScreenWidth - RoundMargin * 2 - (itemCount - 1) * itemMargin) / itemCount
        layout.itemSize = CGSize(width: itemWidth, height: itemHeght)
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
        mainCollectionView.collectionViewLayout = layout
        mainCollectionView.delegate = self
        mainCollectionView.dataSource = self
        mainCollectionView.register(UINib(nibName: "\(PreferenceCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(PreferenceCollectionViewCell.self)")
        mainCollectionView.reloadData()
        
        titleLabel(text: "选择偏好", nil)
        let blurView = DynamicBlurView(frame: bgImageView.bounds)
        blurView.blurRadius = 10
        view.insertSubview(blurView, aboveSubview: bgImageView)
    }
    
    // MARK:- UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return interestMark.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(PreferenceCollectionViewCell.self)", for: indexPath) as? PreferenceCollectionViewCell
        let interestMarkModel:InterestMarkModel = interestMark[indexPath.row] as! InterestMarkModel
        cell?.showData1(isSelect: datas[indexPath.row], imageName: interestMarkModel.icon!, title: interestMarkModel.name!)

        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let interestMarkModel:InterestMarkModel = interestMark[indexPath.row] as! InterestMarkModel
        if datas[indexPath.row] == true{
           datas[indexPath.row] = false
        }
        else{
            datas[indexPath.row] = true
        }
        
        collectionView.reloadData()
    }
    
    override func setNavigation() {
    }

    @IBAction func enterTap(_ sender: UIButton) {
        
        
        if datas.isEmpty{
            self.showToast(msg:"请选择兴趣标签")
            return
        }

        var marks:String = "["
        for i in 0...datas.count-1{
            if datas[i]
            {
                if i > 0 {
                    marks = marks + ","
                }
                let interestMarkModel:InterestMarkModel = interestMark[i] as! InterestMarkModel
                marks = marks + interestMarkModel.id!
            }
        }
        marks = marks + "]"
        
        let requesturl = "\(BaseURL)\(updateUserInfoUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: ["lids":marks] ,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            if(response.error == nil){

                                self.navigationController?.popToRootViewController(animated: true)

                            }else{
                                print("请求失败\(String(describing: response.error))")
                            }

        }
        HUD.show(.label("加载中..."))


        
         navigationController?.popToRootViewController(animated: true)
    }
    @IBAction func skipTap(_ sender: UIButton) {
         navigationController?.popToRootViewController(animated: true)
    }
    
}
